#coding=utf-8
import os
from django.db import models

from stscraper import *
from stvalidator import *
from stutils import todec,data2csv,csv2data

from stsettings import datadir
HISTPRICEDIR = datadir + '/histprice'

import datetime
td = datetime.date.today().isoformat()

class Stcode(models.Model):
    
    '''stcode用于记录 、更新stock代码(code)和名称(name)。
    当新股发行or原有股票更改名称后，数据表中就增加条记录。'''
    
    code = models.CharField(max_length=6)
    name = models.CharField(max_length=20)
    created_at = models.DateField(auto_now_add=True)
    
    class Admin:pass
    class Meta:
        app_label = 'stock'
        
    def __unicode__(self):
        return "%s(%s)"%(self.name, self.code)
    
class Tag(models.Model):
    name = models.CharField(max_length=100)
    class Admin:pass
    class Meta:
        app_label = 'stock'    
    def __unicode__(self):
        return self.name
        
class Share(models.Model):
    
    code = models.CharField(max_length=6, unique=True)
    name = models.CharField(max_length=20)
    ipo = models.DateField()
    created_at = models.DateField(auto_now_add=True)
    
    tags = models.ManyToManyField(Tag, null=True,blank=True)

    class Admin:pass
    class Meta:app_label = 'stock'
    def __unicode__(self):
        return "%s(%s)"%(self.name, self.code)
    
    def save(self):
        
        ipo = get_ipo(self.code)
        isValidExDate(ipo)
        self.ipo = ipo
        
        super(Share, self).save()
        
    def remove_exdays(self):
        eds = self.exday_set.order_by('date')
        for e in eds:
            p = e.price
            if p: p.delete()
        from django.db import connection
        connection.cursor().execute('delete from stock_exday where share_id = %s', (self.id,))
            
    def histprice2db(self, check_local=True):
        from exday import Exday
        from price import Price
        
        #get histprice from local file or sina
        fn= '%s/%s.csv'%(HISTPRICEDIR , self.code)
        if check_local and os.path.exists(fn):
            data = csv2data(fn)
        else:
            print "Now get data from sina."
            ipodate = self.ipo.isoformat()
            data = get_price_since(self.code, ipodate)
            data2csv(data, price_head, fn)
        
        #validation
        for d in data:
            isValidPricefromSina(d)
        
        #data 2 db
        pre = None
        for d in data:
            e = Exday(share=self, date=d[0])   
            if pre: e.pre = pre
            e.save()
            pre = e
            
            v = int(Decimal( d[5] ) * 100 )
            a = int(Decimal( d[6] ) * 10000 )
            
            dd = [todec(i, 2) for i in d[1:5]]
            p = Price(exday=e, start=dd[0], high=dd[1], end=dd[2], low=dd[3], volume=v, amount=a )
            p.save()
    
    def exday_today(self):
        '''得到日期是今日的交易日 object;or None.'''
        from exday import Exday
        try:
            e = self.exday_set.get(date=td)
            return e
        except Exday.DoesNotExist:
            return None
                 
    def prices_between(self, start, end=td):
        eds = self.exday_set.filter(date__gte=start).filter(date__lte=end)
        if eds.count() == 0:return None
        return [e.price for e in eds]
                 
    def has_tdprice(self):
        e = self.exday_today()
        if not e:return False
        if e.price:
            return True
        return False
        
    def tdprice2db(self):
        '''当日price数据入库，如果当天没有交易 raise NoPriceError.'''
        from exday import Exday
        from price import Price
        
        if self.has_tdprice():
            return
            
        data = get_todayprice(self.code)
        #data = get_price_on(self.code, '2007-12-25')
        #put tdprice to histprice csv file
        fn= '%s/%s.csv'%(HISTPRICEDIR , self.code)
        f = open(fn , 'a')
        f.write(','.join(data) )
        f.write('\n')
        f.close()
        
        #validation
        isValidPricefromSina(data)
        
        e = self.exday_today()
        if not e:    
            e = Exday(share=self, date=data[0])
            try:
                pre = self.exday_set.latest('date')
            except Exday.DoesNotExist:
                pre = None
            if pre: e.pre = pre
            e.save()
        
        d = data
        v = int(Decimal( d[5] ) * 100 )
        a = int(Decimal( d[6] ) * 10000 )
        
        dd = [todec(i, 2) for i in d[1:5]]
        p = Price(exday=e, start=dd[0], high=dd[1], end=dd[2], low=dd[3], volume=v, amount=a )
        p.save()
    
    def ts2db(self):
        from fundamental import TradableShare
        data = get_ts(self.code)
        for d in data:
            isValidTS(d)
        for d in data:
            TradableShare.objects.get_or_create(share=self, date=d[0], quantity=int(d[1]))
                
    def get_ts(self, date=None):
        if not date:
            return self.tradableshare_set.latest('date').quantity
        
        for t in self.tradableshare_set.all().order_by('-date'):
            if date >= t.date.isoformat():
                return t.quantity                
    ts = property(fget=get_ts)